<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>watch</title>
  </head>
  <body>
    <div id="app">
      {{ count }} <button @click="count++">count加1</button>
      <hr />
      {{ state.num }} <button @click="state.num++">state.num加1</button>
    </div>
  </body>
  <script src="../lib/vue.global.js"></script>
  <script>
    const { ref, reactive, watch } = Vue;

    Vue.createApp({
      setup() {
        const count = ref(0);
        watch(count, (newVal, oldVal) => {
          // 直接使用 自动解包
          console.log("count", newVal, oldVal);
        });
        watch(
          () => count.value,
          (newVal, oldVal) => {
            // 函数形式需要解包
            console.log("count-fn", newVal, oldVal);
          }
        );

        const state = reactive({ num: 10 });
        watch(
          () => state.num,
          (newVal, oldVal) => {
            console.log("state-num-fn", newVal, oldVal);
          }
        );
        watch(
          () => state,
          (newVal, oldVal) => {
            // 手动深度侦听
            console.log("state-num-fn2", newVal, oldVal);
          },
          { deep: true }
        );

        watch(state, (newVal, oldVal) => {
          // 直接监听响应式对象，会自动启动深度侦听
          console.log("state-num", newVal, oldVal);
        });

        // 监听多个响应式对象
        watch([count, state], ([newCount, newNum], [oldCount, oldNum]) => {
          console.log("newCount", newCount);
          console.log("oldCount", oldCount);
          console.log("newNum", newNum);
          console.log("oldNum", oldNum);
        });
        return {
          count,
          state,
        };
      },
    }).mount("#app");
  </script>
</html>
